<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Auth;
use Cache;
use Cookie;
use DB;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Input;
use Log;
use Mail;
use Redirect;
use Reponse;
use View;
use App\Utils;
use App\Tag;
use App\Task;
use App\TasksTags;
use App\Parsedown;
use App\Link;
use App\Solve;

class SkillController extends Controller
{

    public function show($id)
    {
        $tag = Tag::find($id);
        if ($tag === null || $tag->delete === 1) {
            return view('errors.404');
        }
        if (Auth::user() === null) {
            $userId = -1;
        } else {
            $userId = Auth::user()->id;
        }

        $solves = Solve::where('type', 0)->where('userid', $userId)->get();
        $visible_tasks = array();
        $solved_tasks = array();
        foreach ($solves as $solve) {
            $solved_tasks[$solve->taskid] = 1;
            $visible_tasks[$solve->taskid] = 1;
            $links = Link::where('first', $solve->taskid)->get();
            foreach ($links as $link) {
                $visible_tasks[$link->second] = 1;
            }
        }

        $tasks_tags = TasksTags::where('tagid', $tag->id)->get();
        $tasks = Task::all();

        $tag_tasks = array();
        foreach ($tasks_tags as $tt) {
            foreach ($tasks as $index => $task) {
                if ($tt->taskid === $task->id) {
                    $tag_tasks[$task->id] = [
                        'title' => $task->title,
                        'id' => $tt->taskid,
                        'solved' => isset($solved_tasks[$task->id]),
                        'visible' => isset($visible_tasks[$task->id])
                    ];
                }
            }
        }

        $tag->tasks = $tag_tasks;
        $parsedown = new Parsedown();
        $tag->description = $parsedown->text($tag->description);
        $tag->externallink = $parsedown->text($tag->externallink);
        return view("skills.skill")
            ->with('tag', $tag);
    }
}
